package person.xjl.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import person.xjl.domain.Student;
import person.xjl.domain.Teacher;
import person.xjl.service.StudentService;
import person.xjl.service.TeacherService;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Controller
@SessionAttributes("username")
public class LoginController {
    @Autowired
    private StudentService studentServiceImpl;
    @Autowired
    private TeacherService teacherServiceImpl;
//    @Autowired
//    private TeacherService teacherServiceImpl;
//    @Autowired
//    private AdminService adminServiceImpl;
    @RequestMapping("Login.do")
    public String login(String name, String password, Model model, int type, HttpServletResponse res)
    {
        switch (type)
        {
            //student
            case 0:  Student student=studentServiceImpl.login(name,password);
                if(student==null)
                //登录失败
                {
                    //返回一个错误message
                    //待在login.jsp页面上
                    return "login";
                }
                else
                //登录成功
                {
                    //存cookie
                    Cookie cookie=new Cookie("username",student.getName());
                    res.addCookie(cookie);
                    //session变量保存学生信息,request有效，@SessionAttributes加在类的上面
                    model.addAttribute("username",student.getName());
                    //转到listStudent.jsp页面
                    return "redirect:Student/list.do";
                }
                //teacher
            case  1:
                Teacher teacher=teacherServiceImpl.login(name,password);
                if(teacher==null)
                //登录失败
                {
                    //返回一个错误message
                    //待在login.jsp页面上
                    return "login";
                }
                else
                //登录成功
                {

                    //session变量保存学生信息,request有效，@SessionAttributes加在类的上面
                    model.addAttribute("username",teacher.getName());
                    //转到listTeachers.jsp页面
                    return "redirect:Teacher/list.do";
                }

                //admin
            case 2:

        }
        return "";

    }

}
